<script setup lang="ts">
import { onMounted, ref } from "vue";
import { KeycloakInstance, KeycloakProfile } from "keycloak-js";
import Keycloak from "keycloak-js";
import {
  KeycloakAuthorization,
  KeycloakJwt,
  KeycloakPermission,
} from "./keycloak/keycloak-authz";
import axios from "axios";
import jwtDecode from "jwt-decode";

const keycloak = ref<null | KeycloakInstance>(null);
const message = ref("");
const operationResult = ref("");
const username = ref<string | undefined>("");
const permissions = ref<KeycloakPermission[]>([]);
const logout = () => {
  keycloak.value?.logout();
};

const getProfile = () => {
  axios
    .get<string>("/api/profile", {
      headers: {
        Authorization: `Bearer ${keycloak.value?.token}`,
      },
    })
    .then((res) => {
      operationResult.value = res.data;
    })
    .catch((e) => {
      operationResult.value = e;
    });
};

const getScore = () => {
  axios
    .get<string>("/api/score", {
      headers: {
        Authorization: `Bearer ${keycloak.value?.token}`,
      },
    })
    .then((res) => {
      operationResult.value = res.data;
    })
    .catch((e) => {
      operationResult.value = e;
    });
};

const addScore = () => {
  axios
    .post<string>("/api/score", "88", {
      headers: {
        Authorization: `Bearer ${keycloak.value?.token}`,
      },
    })
    .then((res) => {
      operationResult.value = res.data;
    })
    .catch((e) => {
      operationResult.value = e;
    });
};

const hasPermission = (scope: string, resource: string): boolean => {
  return (
    permissions.value.filter(
      (perm) => perm.scopes.includes(scope) && perm.rsname === resource
    ).length > 0
  );
};

onMounted(() => {
  keycloak.value = Keycloak({
    url: "http://localhost:18080",
    realm: "keycloak-learn",
    clientId: "chapter-4",
  });
  keycloak.value
    .init({
      onLoad: "login-required",
    })
    .then((authenticated: boolean) => {
      keycloak.value?.loadUserProfile().then((profile: KeycloakProfile) => {
        username.value = profile.username;
      });
      message.value = `Authenticated: ${authenticated}`;
      if (keycloak.value) {
        const authz = new KeycloakAuthorization(keycloak.value);
        authz.init().then(() => {
          authz.entitlement("chapter-3").then((rpt) => {
            const keycloakJwt = jwtDecode<KeycloakJwt>(rpt);
            permissions.value = keycloakJwt.authorization.permissions;
          });
        });
      }
    })
    .catch(function () {
      message.value = "failed to initialize";
    });
});
</script>

<template>
  {{ message }}
  <hr />
  Hi {{ username }}
  <hr />
  <button v-if="hasPermission('GET', 'Profile')" @click="getProfile">
    Get profile
  </button>
  <button v-if="hasPermission('GET', 'Score')" @click="getScore">
    Get score
  </button>
  <button v-if="hasPermission('POST', 'Score')" @click="addScore">
    Add score
  </button>
  <br />
  {{ operationResult }}
  <hr />
  <button @click="logout">Logout</button>
</template>
